package com.ccy_blog.back.controller;


import com.ccy_blog.back.bean.Comment;
import com.ccy_blog.back.bean.User;
import com.ccy_blog.back.service.CommentService;
import com.ccy_blog.base.bean.ResultVo;
import com.ccy_blog.base.exception.BlogException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    //前端评论展示
    @RequestMapping("/comment/allList")
    @ResponseBody
    public List<Comment> allList(){
        List<Comment> comments = commentService.list("1");
        return comments;
    }
    //后台评论展示
    @RequestMapping("/commnet/list")
    @ResponseBody
    public PageInfo<Comment> list(int page, int pageSize, HttpSession session){
        //获取当前登录用户
        User user = (User) session.getAttribute("user");
        //参数1:当前页码 参数2:每页记录数 pageSize 该方法等同于 limit a,b
        PageHelper.startPage(page,pageSize);
        List<Comment> comments = commentService.list(user.getUid());
        PageInfo<Comment> pageInfo = new PageInfo<>(comments);
        return pageInfo;
    }

    //异步删除评论
    @RequestMapping("/comment/deleteById")
    @ResponseBody
    public ResultVo deleteById(String cid){
        ResultVo resultVo = new ResultVo();
        try {
            commentService.deleteById(cid);
            resultVo.setOk(true);
            resultVo.setMess("删除评论成功");
        }catch (BlogException e){
            resultVo.setMess(e.getMessage());
        }
        return resultVo;
    }

    //异步发布文章
    @RequestMapping("/comment/save")
    public String save(String editorContent, HttpSession session){
        Comment comment = new Comment();
        comment.setContent(editorContent);
        ResultVo resultVo = new ResultVo();
        try {
            //获取登录用户
            User user = (User) session.getAttribute("user");
            comment.setUsername(user.getUsername());
            resultVo.setOk(commentService.save(comment));
                resultVo.setMess("发布评论成功");
            resultVo.setT(comment);
        }catch (BlogException e){
            resultVo.setMess(e.getMessage());
        }
        return "/workbench/comment/comment";
    }
}
